/*
 * create by straysnail
 * 2022/3/20
 */
#define INA 7  //宏定义电机驱动的引脚
#define ENA 6
#define INB 8  
#define ENB 5 

#define wayPin1 9  //宏定义循迹传感器的引脚
#define wayPin2 10
boolean L_tval = 0;
boolean R_tval = 0;

void setup() {
  Serial.begin(9600);
  pinMode(INA, OUTPUT);
  pinMode(ENA, OUTPUT);
  pinMode(INB, OUTPUT);
  pinMode(ENB, OUTPUT);
  pinMode(wayPin1, INPUT);
  pinMode(wayPin2, INPUT);
}

void loop() {
  car_circle();
}

void car_circle()
{
  L_tval = digitalRead(wayPin1);
  R_tval = digitalRead(wayPin2);
  Serial.print(L_tval);
  Serial.print("  ");
  Serial.println(R_tval);
  delay(100);
  if((L_tval == 1) && (R_tval == 1))
  {
    car_back();
    delay(100);
    car_left();
    delay(200);
  }
  else if((L_tval == 1) && (R_tval == 0))
  {
    car_right();
    delay(100);
  }
  else if((L_tval == 0) && (R_tval == 1))
  {
    car_left();
    delay(100);
  }
  else if((L_tval == 0) && (R_tval == 0))
  {
    car_forward();
  }
}

//The little snail moves forward
void car_forward()
{
  digitalWrite(INA, HIGH);  //Output high level and control the left motor forward
  analogWrite(ENA, 50);    //PWM output to control the speed of left motor
  digitalWrite(INB, HIGH);  //Output high level and control the right motor forward
  analogWrite(ENB, 50);    //PWM output to control the speed of right motor
}

void car_back()
{
  digitalWrite(INA, LOW); 
  analogWrite(ENA, 50);    
  digitalWrite(INB, LOW);  
  analogWrite(ENB, 50);
}


//The little snail turns left
void car_left()
{
  digitalWrite(INA, LOW);
  analogWrite(ENA, 70);
  digitalWrite(INB, HIGH);
  analogWrite(ENB, 80);
}
//The little snail turns right
void car_right()
{
  digitalWrite(INA, HIGH);
  analogWrite(ENA, 80);
  digitalWrite(INB, LOW);
  analogWrite(ENB, 70);
}
//Stop
void car_stop()
{
  digitalWrite(INA, HIGH);
  analogWrite(ENA, 0);
  digitalWrite(INB, HIGH);
  analogWrite(ENB, 0);
}
